﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Approval;
using B.S.BasicData.Domain.Entity.Approval;
using B.S.BasicData.Domian.Entitys;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.Approval
{
    public class UpdateApprovalHandler : IRequestHandler<UpdateApprovalCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UsersModel> _userRepository;
        private readonly IBaseRepository<ApprovalModel> _approvalRepository;
        private IMapper _mapper;

        public UpdateApprovalHandler(IBaseRepository<UsersModel> userRepository,
            IBaseRepository<ApprovalModel> approvalRepository, IMapper mapper)
        {
            _userRepository = userRepository;
            _approvalRepository = approvalRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 申请单修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(UpdateApprovalCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var approval =_approvalRepository.GetAll().Where(p=>p.Id == request.Id).FirstOrDefault();
            if (approval != null)
            {
                approval = _mapper.Map(request, approval);
            }
            var res = _approvalRepository.Update(approval);
            if (res > 0)
            {
                result.Data = res;
                result.Code = StatusEnum.OK;
                result.Message = "修改成功";
            }
            else
            {
                result.Data = res;
                result.Code = StatusEnum.Fail;
                result.Message = "修改失败";
            }
            return Task.FromResult(result);


        }
    }
}
